
import { useState, useCallback, useEffect } from "react";

import { message } from "antd";
import { TimeLine } from "@/types/content/timeLine";
import { queryTimeLineList, removeTimeLine } from "@/api/content/timeLine";
import { LOVE_TIME_LINE_TYPE } from "@/constants/configKey.constant";
import dayjs from "dayjs";
export const useTimeLine = () => {
  const [messageApi] = message.useMessage();
  const [loading, setLoading] = useState(false);
  const [searchForm,setSearchForm] = useState<TimeLine.Query>({ type: LOVE_TIME_LINE_TYPE, time: [], content: '' })
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  });
  const [tableData, setTableData] = useState<TimeLine.Row[]>([]);
  /**
   * 获取标签列表
   */
  const getTableList = useCallback(async () => {
    const { time, content } = searchForm
    const params = {
        // 页码
        pageNo: pagination.pageNo || 1,
        pageSize: pagination.pageSize || 10,
        type: LOVE_TIME_LINE_TYPE,
        content,
        startTime: time&&time[0]?dayjs(time[0]).format('YYYY-MM-DD HH:mm:ss') : '',
        endTime: time&&time[1]?dayjs(time[1]).format('YYYY-MM-DD HH:mm:ss') : ''
    };
    setLoading(true);
    const res = await queryTimeLineList(params);
    setLoading(false);
    if (res.code === 200) {
      setTableData(res.data?.rows || []);
      setPagination({
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        total: res.data.total
      })

    }
  }, [pagination.pageNo, pagination.pageSize, searchForm]);
  /**
* 删除评论
* @param id 
*/
  const removeTimeLineInf = async (row: TimeLine.Row) => {
    setLoading(true)
    const res = await removeTimeLine(row.id)
    setLoading(false)
    if (res.code === 200) {
      messageApi.success('删除成功')
      if (tableData.length === 1) {
        setPagination({
          pageNo: Math.max(1, pagination.pageNo - 1),
          pageSize: pagination.pageSize,
          total: pagination.total
        })
      } else {
        getTableList()
      }
    }
  }
  useEffect(() => {
    getTableList();
  }, [getTableList]);
  return {
    loading, tableData, pagination, setPagination,removeTimeLineInf,setSearchForm,getTableList
  }
}